package com.rlz.net.Interceptor

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import com.rlz.net.NetManager
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * Created by RLZ
 * on 2021/4/16
 *
 */
class NetOfflineInterceptor : Interceptor {

    //离线的时候的缓存的过期时间
    private var mOfflineCacheTime = 0

    companion object {
        val instance: NetOfflineInterceptor by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            NetOfflineInterceptor()
        }
    }

    fun setOfflineCacheTime(time: Int) {
        mOfflineCacheTime = time
    }

    @SuppressLint("MissingPermission")
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request: Request = chain.request()
        val conn = NetManager.sApplication!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork: NetworkInfo? = conn.activeNetworkInfo
        if (activeNetwork?.isConnectedOrConnecting != true) {
            if (mOfflineCacheTime != 0) {
                val temp = mOfflineCacheTime
                request = request.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=$temp")
                        .build()
                mOfflineCacheTime = 0
            } else {
                request = request.newBuilder()
                        .header("Cache-Control", "no-cache")
                        .build()
            }
        }
        return chain.proceed(request)
    }
}